package com.iwomy.secureplat.platform.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.iwomy.secureplat.common.data.tenant.TenantContextHolder;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.dto.BasicConsumptionRecordDTO;
import com.iwomy.secureplat.platform.entity.BasicConsumptionRecordEntity;
import com.iwomy.secureplat.platform.entity.BasicInventoryListEntity;
import com.iwomy.secureplat.platform.mapper.BasicConsumptionRecordMapper;
import com.iwomy.secureplat.platform.service.BasicConsumptionRecordService;
import com.iwomy.secureplat.platform.service.BasicDeviceService;
import com.iwomy.secureplat.platform.utils.DataScopeUtils;
import com.iwomy.secureplat.platform.utils.RemoteDeptUtils;
import com.iwomy.secureplat.platform.vo.BasicConsumptionRecordVO;
import com.iwomy.secureplat.platform.vo.BasicDeviceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 短信语音消费记录详情
 *
 * @author pig
 * @date 2023-12-08 09:35:31
 */
@Service
public class BasicConsumptionRecordServiceImpl extends ServiceImpl<BasicConsumptionRecordMapper, BasicConsumptionRecordEntity> implements BasicConsumptionRecordService {

	@Autowired
	private BasicDeviceService basicDeviceService;

	@Autowired
	private RemoteDeptUtils remoteDeptUtils;

	@Override
	public Page<BasicConsumptionRecordVO> getBasicConsumptionRecordPage(Page page, BasicConsumptionRecordDTO basicConsumptionRecord) {
		MPJLambdaWrapper<BasicConsumptionRecordEntity> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(BasicConsumptionRecordEntity.class);
		wrapper.in(BasicConsumptionRecordEntity::getDeptId, SecurityUtils.getUser().getDeptId());

		List<?> lists = DataScopeUtils.getList();
		if (lists != null && !lists.isEmpty()) {
			wrapper.in(BasicInventoryListEntity::getCustomerDeptId, lists);
		}

		if (ArrayUtil.isNotEmpty(basicConsumptionRecord.getCreateTime())) {
			wrapper.ge(BasicConsumptionRecordEntity::getCreateTime, basicConsumptionRecord.getCreateTime()[0]).le(BasicConsumptionRecordEntity::getCreateTime,
					basicConsumptionRecord.getCreateTime()[1]);
		}
		if (ObjectUtil.isNotEmpty(basicConsumptionRecord.getUsedType())) {
			wrapper.eq(BasicConsumptionRecordEntity::getUsedType, basicConsumptionRecord.getUsedType());
		}

		if (StrUtil.isNotEmpty(basicConsumptionRecord.getDeptName())) {
			List<Long> deptId = (List<Long>) remoteDeptUtils.getDeptId(basicConsumptionRecord.getDeptName()).getData();
			if (deptId != null && !deptId.isEmpty()) {
				wrapper.in(BasicConsumptionRecordEntity::getCustomerDeptId, deptId);
			} else {
				return page;
			}
		}
		return wrapperPage(page, wrapper);
	}

	private Page<BasicConsumptionRecordVO> wrapperPage(Page page, MPJLambdaWrapper<BasicConsumptionRecordEntity> wrapper) {
		Long tenantId = TenantContextHolder.getTenantId();
		TenantContextHolder.clear();
		Page<BasicConsumptionRecordVO> basicConsumptionRecordPage = this.getBaseMapper().selectJoinPage(page, BasicConsumptionRecordVO.class, wrapper);
		List<BasicConsumptionRecordVO> records = basicConsumptionRecordPage.getRecords();
		TenantContextHolder.setTenantId(tenantId);
		records.stream().filter(record -> record.getCustomerDeptId() != null)
				.forEach(record -> record.setCustomerDeptName(remoteDeptUtils.getDeptName(record.getCustomerDeptId())));
		records.stream().map(record -> {
			if (record.getDeviceId() != null) {
				Long deviceId = record.getDeviceId();
				BasicDeviceVO basicDevice = basicDeviceService.getByIds(deviceId);
				if (basicDevice!=null){
					record.setDeptName(basicDevice.getDeptName());
					record.setDeviceType(basicDevice.getDeviceType());
					record.setDeviceModelName(basicDevice.getDeviceModelName());
					record.setImei(basicDevice.getImei());
				}
			}
			return record;
		}).collect(Collectors.toList());

		return basicConsumptionRecordPage;
	}

	//查询租户使用设备数
	@Override
	public Map<String, Integer> tenantQuerySmsTtsCount(Long deptId) {
		QueryWrapper<BasicConsumptionRecordEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("dept_id", deptId);
		wrapper.in("used_type", 10, 30, 50, 60);
		wrapper.in("consume_type", 20);
		wrapper.between("create_time",
				LocalDateTime.of(LocalDate.now().withDayOfMonth(1), LocalTime.MIN),
				LocalDateTime.of(LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()), LocalTime.MAX)
		);
		Long tenantId = TenantContextHolder.getTenantId();
		TenantContextHolder.clear();
		List<BasicConsumptionRecordEntity> inventoryCount = this.getBaseMapper().selectList(wrapper);
		TenantContextHolder.setTenantId(tenantId);
		Integer sms = inventoryCount.stream()
				.filter(record -> record.getNotificationType() == 10)
				.filter(record -> record.getSmsNumber() != 999999)
				.mapToInt(BasicConsumptionRecordEntity::getSmsNumber)
				.sum();
		Integer tts = inventoryCount.stream()
				.filter(record -> record.getNotificationType() == 20)
				.filter(record -> record.getTtsNumber() != 999999)
				.mapToInt(BasicConsumptionRecordEntity::getTtsNumber)
				.sum();

		Map<String, Integer> resultMap = new HashMap<>();
		resultMap.put("thisMonthSmsTotal", sms);
		resultMap.put("thisMonthTtsTotal", tts);
		return resultMap;
	}

}